
import { util } from '../tool'
 
class common {
	
	constructor(){

	}

	// 验证来源 && 验证签名
    async checkRequestUrl(ctx,next){
        let verSource = this.verSource(ctx)
        let checkSigin = this.checkSiginHttp(ctx);

        if(verSource&&checkSigin){
            return next();
        }else{
        	console.log('域名来源验证有误')
        }


    }
    // 检查接口来源权限
    checkReferer(cxt){
        let begin     = false;
        let url       = SYSTEM.ORIGIN
        let header   = cxt.request.header

        if (header.host.split(':')[0] === 'localhost' || header.host.split(':')[0] === '127.0.0.1') {
            url = SYSTEM.TESTORIGIN
        } else {
            url = SYSTEM.DISTORIGIN
        }
        if(header.referer == url){
            begin = true;
        }
        return begin;
    }
    // 验证域名来源、
    verSource(ctx){
        let referer = this.checkReferer(ctx);
        if(!referer){
            ctx.body = this.result({
                code:1001,
                desc:'域名来源未通过！'
            });
            return false;
        }else{
            return true;
        }
    };

    // http 签名验证验证参数
    checkSiginHttp(ctx){
        let datas = ctx.request.body

        if(!datas){
            ctx.body = this.result({
                code:1001,
                desc:'缺少必要的验证签名参数！'
            });
            return false;
        }

        let getSign = null;

        if(typeof(data)=='string'){
            getSign = JSON.parse(datas.getSign)
        }else{
            getSign = datas.getSign
        }

        if(!getSign || !getSign.time || !getSign.random || !getSign.paySign){
            return false;   
        };
        let sigin=this.signwx({
            name:'wangwei',
            company:'morning-star',
            time:getSign.time,
            random:getSign.random
        });
        if(sigin.paySign === getSign.paySign){
            return true;    
        }else{
            ctx.body = this.result({
                code:1001,
                desc:'签名验证未通过！'
            });
            return false;
        }
    }

}

module.exports = new common();